﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace iLangl.Model
{
	public class SyncedMutliWaysData : SyncedOneWayData
	{
		public SyncedMutliWaysData()
			: base()
		{
			objects = new Hashtable();
			objectsSubscribers = new Hashtable();
			subscribers = new Hashtable();
		}
		public IList<String> ConsumersList;

		private Hashtable objectsSubscribers;
		private Hashtable subscribers;
		private Hashtable objects;
		

		public void AddConsumer(String objectKey, Object value, String subscriberId)
		{
			//Register subscriber
			subscribers[subscriberId] = true;
			objects[objectKey] = value;

			List<String> results = (List<String>)objectsSubscribers[objectKey];

			if (results == null)
			{
				results = new List<string>();
				objectsSubscribers[objectKey] = results;
			}

			bool find = false;
			foreach (String _consumerId in results)
			{
				if(string.Compare(subscriberId, _consumerId, true) == 0)
				{
					find = true;
					break;
				}
			}

			if (!find)
			{
				results.Add(subscriberId);
			}
		}

		public IList<String> GetSubscribers(String objectKey)
		{
			return (IList<String>)objectsSubscribers[objectKey];
		}


		public IList<SyncedOneWayData> PrepareDataToSend()
		{
			IList<SyncedOneWayData> result = new List<SyncedOneWayData>();

			foreach (String susbscriber in subscribers.Keys)
			{
				SyncedOneWayData data = new SyncedOneWayData();
				IList<Company> companies = new List<Company>();
				IList<Project> projects = new List<Project>();

				foreach (String objectkeys in objectsSubscribers.Keys)
				{
					List<String> results = (List<String>)objectsSubscribers[objectkeys];

					foreach (string subsubscriber in results)
					{
						if (String.Compare(susbscriber, subsubscriber, true) == 0)
						{
							Object oresult = objects[objectkeys];

							if (oresult is Project)
							{
								projects.Add(oresult as Project);
							}

							if (oresult is Company)
							{
								companies.Add(oresult as Company);
							}

						}
					}
				}

				data.Subscriber = susbscriber;
				data.Companies = companies.ToArray();
				data.Projects = projects.ToArray();
				data.TimeSpans = TimeSpans;

				result.Add(data);
			}

			return result;
		}
	}
}
